package cn.tedu.restaurant.controller;


import cn.tedu.restaurant.common.JsonResult;
import cn.tedu.restaurant.entity.User;
import cn.tedu.restaurant.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author JachinLin
 * @since 2020-10-05
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    public static final Integer SUCCESS = 200;

    @RequestMapping("/reg")
    public JsonResult<Void> reg(User user) {
        JsonResult<Void> result = new JsonResult<Void>(SUCCESS);
        userService.register(user);
        return result;
    }

    @RequestMapping("/login")
    public JsonResult<User> login(String phone, String password, HttpSession session) {
        User user = userService.login(phone, password);
        session.setAttribute("uid", user.getUid());
        session.setAttribute("phone", user.getPhone());
        session.setAttribute("username", user.getUsername());
        return new JsonResult<User>(SUCCESS, user);
    }



    @RequestMapping("/change_password")
    public JsonResult<Void> updatePassword(@RequestParam("oldPassword") String oldPassword,
        @RequestParam("newPassword") String newPassword, HttpSession session) {
        JsonResult<Void> result = new JsonResult<Void>(SUCCESS);
        Integer uid = Integer.valueOf(session.getAttribute("uid").toString());
        String username = session.getAttribute("username").toString();
        userService.changePassword(uid, oldPassword, newPassword, username);
        return result;
    }

    @RequestMapping("/changeUserName")
    public JsonResult<Void> updateUserName(@RequestParam("newUserName")String username,HttpSession session) {
        JsonResult<Void> result = new JsonResult<Void>(SUCCESS);
        Integer uid = Integer.valueOf(session.getAttribute("uid").toString());
        session.setAttribute("username",username);
        String phone = session.getAttribute("phone").toString();
        userService.changeUserName(uid,username,phone);
        return result;
    }

    @RequestMapping("/getUserInfo")
    public JsonResult<User> getUserInfo(HttpSession session) {
        Integer uid = Integer.valueOf(session.getAttribute("uid").toString());
        User user = userService.getByUid(uid);
        return new JsonResult<User>(SUCCESS, user);
    }




}
